package com.darrenchan.spark

import _root_.kafka.serializer.StringDecoder
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
  * 整合Flume,Kafka,Spark Streaming
  */
object KafkaStreamingApp {
  def main(args: Array[String]): Unit = {

    if(args.length != 2) {
      System.err.println("Usage: KafkaReceiverWordCount <brokers> <topics>")
      System.exit(1)
    }

    val Array(brokers, topics) = args

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("KafkaStreamingApp")
    val ssc = new StreamingContext(sparkConf, Seconds(5))

    val kafkaParams = Map[String, String]("metadata.broker.list"->brokers)
    val topicsSet = topics.split(",").toSet
    //Spark Streaming如何对接Kafka
    val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topicsSet)

    //messages.print() //(null,b c d d d f f g s s s s s)
    messages.map(_._2).count().print
    /*
        (d,3)
        (b,1)
        (f,2)
        (s,5)
        (g,1)
        (c,1)
     */

    ssc.start()
    ssc.awaitTermination()
  }
}
